import { useEffect, useMemo, useRef, useState, useContext } from 'react';
import { getMessage } from '@inbiz/react';
import { Input, message, Modal, Tag } from '@inbiz/antd';
import type { InputRef } from '@inbiz/antd';
import DelTag from './components/Icon/DelTag';
import tableApi from './serviceApi';
import { InBizTableCtx, InBizTableRefCtx, TableCtx } from '../../context';
import { ConditionsType } from '../../interfaces';
import { getSearchValues, setComponentsValue } from '../../util';
import { useColumnConfig } from '../../hooks';
import { ExclamationCircleFilled } from '@ant-design/icons';
import '../../style.less'


const SearchTag = (props: { fetchData: () => void }) => {
  const { inbiz, clickSearch, controlId } = useContext(InBizTableCtx);
  const { tableTopRef, searchRef } = useContext(InBizTableRefCtx);
  const { queryFields } = useColumnConfig();
  const { fetchTagData } = useContext(TableCtx);
  const [editInputIndex, setEditInputIndex] = useState(-1);
  const [editInputValue, setEditInputValue] = useState('');
  const [selectTag, setSelectTag] = useState<null | string>(null);
  const editInputRef = useRef<InputRef>(null);
  let timer: any = null;
  const pageTag = useMemo(() => {
    return tableTopRef.current?.data;
  }, [tableTopRef.current?.data]);

  const tagList: {
    name: string;
    data: ConditionsType[];
  }[] = useMemo(() => {
    const data = tableTopRef.current?.data || {};
    return data[controlId] || [];
  }, [tableTopRef.current?.data]);

  const handleClose = (removedTag: string) => {
    Modal.confirm({
      className:'inbiz-table-save-search-modal',
      title: getMessage('Table.tips.confirmDeleteTag'),
      icon: <ExclamationCircleFilled />,
      okText: getMessage('Table.sure'),
      cancelText: getMessage('Table.cancel'),
      onOk() {
        if (selectTag === removedTag) {
          setSelectTag(null);
        }
        const newTags = tagList.filter((tag) => tag.name !== removedTag);
        tableApi
          .saveTableSearch(inbiz, JSON.stringify({ ...pageTag, [controlId]: newTags }))
          .then((res) => {
            message.success(getMessage('Table.tips.deleteSucceeded'));
            fetchTagData && fetchTagData();
          });
      },
    });
  };

  const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEditInputValue(e.target.value);
  };

  const handleEditInputConfirm = () => {
    const newTags = [...tagList];
    const inputValue = editInputValue?.trim?.() || '';
    if (inputValue == '') {
      message.error(getMessage('Table.tips.noName'));
      return;
    }
    // 判断是否有修改
    if (newTags[editInputIndex].name == inputValue) {
      setEditInputIndex(-1);
      return;
    }
    if (newTags.some((tag) => tag.name == inputValue)) {
      message.error(getMessage('Table.tips.repeatName'));
      return;
    }
    newTags[editInputIndex].name = inputValue;
    tableApi
      .saveTableSearch(inbiz, JSON.stringify({ ...pageTag, [controlId]: newTags }))
      .then((res) => {
        fetchTagData && fetchTagData();
        if (selectTag == '') {
          setSelectTag(null);
        }
        setEditInputIndex(-1);
      });
  };
  const onDoubleClick = (
    e: React.MouseEvent<HTMLSpanElement, MouseEvent>,
    index: number,
    tag: string,
  ) => {
    clearTimeout(timer);
    setEditInputIndex(index);
    setEditInputValue(tag);
    e.preventDefault();
  };
  const onClick = (tag: { name: string; data: any[] }) => {
    clearTimeout(timer);
    timer = setTimeout(function () {
      setSelectTag((oldTag: null | string) => {
        if (oldTag && tag.name == oldTag) {
          return '';
        }
        return tag.name;
      });
    }, 500);
  };

  useEffect(() => {
    tableTopRef.current = {
      ...tableTopRef.current,
      selectTag,
      setSelectTag,
    };
    if (selectTag === null) {
      return;
    }
    if (selectTag != '') {
      (inbiz?.reset as any)?.(controlId);
      const tag = tagList.find((tag) => tag.name == selectTag);
      // 临时处理成员选择组件调用setValueToID方法，因该方法异步，导致查询时无法获取数据
      let menber = null;
      menber = setComponentsValue({ComponentValues: tag?.data, inbiz})
      getSearchValues({ inbiz, controlId, searchRef, queryFields, initCondition: menber });
      if (clickSearch) {
        props.fetchData();
      }
    } else {
      if (clickSearch) {
        tableTopRef.current.onReset();
      } else {
        (inbiz?.reset as any)?.(controlId);
      }
    }
  }, [selectTag]);

  useEffect(() => {
    editInputRef.current?.focus();
  }, [editInputIndex]);

  useEffect(() => {
    fetchTagData && fetchTagData();
    return () => {
      clearTimeout(timer);
    };
  }, []);
  return (
    <div className="search-tags">
      {tagList.map((tag, index) => {
        if (editInputIndex === index) {
          return (
            <Input
              ref={editInputRef}
              key={tag.name}
              size="small"
              className="tag-input"
              value={editInputValue}
              onChange={handleEditInputChange}
              onBlur={handleEditInputConfirm}
              onPressEnter={handleEditInputConfirm}
            />
          );
        }

        return (
          <Tag
            className={selectTag == tag.name ? 'select-tag edit-tag' : 'edit-tag'}
            key={tag.name}
            closable={true}
            closeIcon={<DelTag />}
            onClose={(e) => {
              e.preventDefault();
              handleClose(tag.name);
            }}
          >
            <span
              onDoubleClick={(e) => {
                onDoubleClick(e, index, tag.name);
              }}
              onClick={() => {
                onClick(tag);
              }}
              title={tag.name}
            >
              {tag.name}
            </span>
          </Tag>
        );
      })}
    </div>
  );
};

export default SearchTag;
